/**
 * Project 67th
 */


#include "TcpConnection.h"
#include <sstream>
using std::ostringstream;

/**
 * TcpConnection implementation
 */


/**
 * @param fd
 */
TcpConnection::TcpConnection(int fd) 
: _sockIO(fd)
, _sock(fd)
, _localAddr(getLocalAddr())
, _peerAddr(getPeerAddr())
{

}

TcpConnection::~TcpConnection() {

}

/**
 * @return string
 */
string TcpConnection::receive() {
    char buff[65535] = {0};
    _sockIO.readLine(buff,sizeof(buff));
    return string(buff);
}

/**
 * @param msg
 * @return void
 */
void TcpConnection::send(const string & msg) {
    _sockIO.writen(msg.c_str(),msg.size());
}


string TcpConnection::toString()
{
    ostringstream oss;
    oss << _localAddr.getIp() << ":"
        << _localAddr.getPort() << "------>"
        << _peerAddr.getIp() << ":"
        << _peerAddr.getPort();
    return oss.str();
}

InetAddress TcpConnection::getLocalAddr()
{
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);

    //获取本端的地址信息
    int ret = getsockname(_sock.getFd(),
                          (struct sockaddr*)&addr,
                          &len);
    if(ret < 0)
    {
        perror("getsockname");
    }

    return InetAddress(addr);
}

InetAddress TcpConnection::getPeerAddr()
{
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);

    //获取对端的地址信息
    int ret = getpeername(_sock.getFd(),
                          (struct sockaddr*)&addr,
                          &len);
    if(ret < 0)
    {
        perror("getsockname");
    }

    return InetAddress(addr);
}

//进行一次预读取（复制式）
bool TcpConnection::isClosed()
{
    char buff[5] = {0};
    int ret = ::recv(_sock.getFd(),buff,sizeof(buff),MSG_PEEK);
    return 0 == ret;
}


void TcpConnection::setNewConnectionCallback(const TcpConnectionCallback & cb)
{
    //这样写会导致EventLoop将自己的function所关联的目标的调用权
    //移交给TcpConnection，从而变成空的function
    //
    //当产生第二条连接时，再进行转接，第二个TcpConnection内部
    //的function也会成为空的function
    /* _onNewConnection = std::move(cb); */
    _onNewConnection = cb;
}

void TcpConnection::setMessageCallback(const TcpConnectionCallback & cb)
{
    _onMessage = cb;
}
void TcpConnection::setCloseCallback(const TcpConnectionCallback & cb)
{
    _onClose = cb;
}


void TcpConnection::handleNewConnectionCallback()
{
    if(_onNewConnection)
    {
        /* _onNewConnection(shared_ptr<TcpConnection>(this)); */

        //以合法的形式得到一个管理本对象的shared_ptr
        _onNewConnection(shared_from_this());
    }
    else
    {
        printf("_onNewConnection是空的function\n");
    }
}
void TcpConnection::handleMessageCallback()
{
    if(_onMessage)
    {
        _onMessage(shared_from_this());
    }
    else
    {
        printf("_onMessage是空的function\n");
    }
}
void TcpConnection::handleCloseCallback()
{
    if(_onClose)
    {
        _onClose(shared_from_this());
    }
    else
    {
        printf("_onClose是空的function\n");
    }
}
